import React, {useEffect, useState} from 'react';
import {App, Button, Card, Form, InputNumber, Spin} from "antd";
import LogFactory from "log/LogFactory";
import BaseEntity from "type/entity";
import {FormEnhanceProps} from "./FormEnhanceProps";
import {useAppDispatch} from "storage/redux/hook";
import {Link, useLocation, useNavigate} from "react-router-dom";
import TextArea from "antd/es/input/TextArea";
import {compareObject} from "util/compare";

const log = LogFactory.getLogger("FormEnhance");
const FormEnhance = <T extends BaseEntity>(props: FormEnhanceProps<T>) => {

    const initData = useLocation().state;
    log.debug("FormEnhance组件渲染,初始化数据: ", initData);
    const [ loading, setLoading ] = useState<boolean>(false);
    const [form] = Form.useForm<T>();
    const { message } = App.useApp();
    const dispatch = useAppDispatch();
    const navigate = useNavigate();
    useEffect(()=>{
        form.setFieldValue("order", 1);
        if (initData){
            if (props.initDataConverter){
                const hd = props.initDataConverter({...initData});
                form.setFieldsValue(hd as object);
            }else {
                form.setFieldsValue(initData);
            }
        }
        props.componentReady?.(form);
    }, []);

    const onFinish = async (values: T) => {
        // 处理备注信息
        if (values.remark){
            values.remark = values.remark.trim();
        }
        if (props.formDataConverter){
            values = props.formDataConverter(values);
        }
        if (initData){
            // 如果有初始化数据,则为修改操作
            await updateDataHandler(values);
        }else {
            // 如果没有初始化数据,则为添加操作
           await addDataHandler(values);
        }
    };
    /** 修改数据的处理方法 */
    const updateDataHandler = async (values: T) => {
        // log.debug("修改数据表单处理方法:", values);
        const compRes = compareObject(initData, values);
        if (compRes === null){
            log.debug("数据没有变化,不需要修改");
            message.info("数据没有变化,不需要修改");
            return;
        }else {
            setLoading(true);
            const result = await dispatch(props.requestAction(compRes as T)).unwrap();
            if(result.success && result.data === 1){
                message.success("修改成功");
                navigate("..");
            }else{
                message.warning("修改失败");
            }
            setLoading(false);
        }
    };

    /** 添加数据的处理方法 */
    const addDataHandler = async (values: T) => {
        log.debug("添加数据表单处理方法:", values);
        setLoading(true);
        const result = await dispatch(props.requestAction(values)).unwrap();
        if(result.success && result.data){
            setLoading(false);
            if (props.addSuccess){
                props.addSuccess(result.data, message, dispatch);
            }
            message.success("添加成功");
            navigate("..");
        }else{
            log.warn("添加数据失败:", result);
            message.warning("添加失败");
        }
        setLoading(false);
    };

    return (
        <Card title={props.title} extra={ <Link to={props.backupUrl ?? ".."}>{props.backupText ?? "backup"}</Link> }>
            <Spin spinning={loading}>
                <Form<T>
                    form={form}
                    labelCol={{ span: 4}}
                    wrapperCol={{ span: 14 }}
                    layout={"horizontal"}
                    style={{ maxWidth: "800px", margin: "auto" }}
                    initialValues={props.initialValues}
                    onFinishFailed={props.onError}
                    onFinish={onFinish}
                >
                    {props.children}
                    <Form.Item<BaseEntity> label={"数据排序"} name={"order"} required={true} rules={[{required: true, message: "排序字段必须填写!"}]}>
                        <InputNumber min={0} addonAfter={"ORDER"} />
                    </Form.Item>
                    <Form.Item<BaseEntity> label={"备注信息"} name={"remark"}>
                        <TextArea rows={3}/>
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                        <Button loading={loading} htmlType='submit' type='primary'>
                            提交表单
                        </Button>
                        <Button style={{ margin: '0 8px' }} htmlType='reset' type='link'>
                            重置
                        </Button>
                    </Form.Item>
                </Form>
            </Spin>
        </Card>
    );
};

export default FormEnhance;